// Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
using System.Security.Principal;

namespace SSISAccess
{
    internal class LocalDComGroup : IDisposable
    {
        public const string GroupName = "Distributed COM Users";
        private string userPath;
        private DirectoryEntry dcomGroup;
        private AccountInfo userAccount;

        private LocalDComGroup() { }
        public LocalDComGroup(AccountInfo userAccount)
        {
            this.userAccount = userAccount;
        }

        public void Dispose()
        {
            if (this.dcomGroup != null)
            {
                this.dcomGroup.Dispose();
                this.dcomGroup = null;
            }
        }

        private string ResolveUserPath()
        {
            string userPath = String.Format("WinNT://{0}/{1}", this.userAccount.DomainName, this.userAccount.UserName);

            using (DirectoryEntry userObject = new DirectoryEntry(userPath))
            {
                return (string)userObject.InvokeGet("ADsPath");
            }
        }

        public void AddUserToGroup()
        {
            this.DcomGroup.Invoke("Add", new object[] { this.UserPath });
        }

        public bool IsUserInGroup()
        {
            return (bool)this.DcomGroup.Invoke("IsMember", new object[] { this.UserPath });
        }

        private DirectoryEntry DcomGroup
        {
            get
            {
                if (this.dcomGroup == null)
                {
                    this.dcomGroup = new DirectoryEntry("WinNT://" + Environment.MachineName + "/" + GroupName + ",group");
                }
                return this.dcomGroup;
            }
        }

        private string UserPath
        {
            get
            {
                if (this.userPath == null)
                {
                    this.userPath = ResolveUserPath();
                }
                return this.userPath;
            }
        }
    }
}
